package com.xbongbong.crm.help;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.StageLogEntity;
import com.xbongbong.paas.domain.entity.StageProcessEntity;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.StageProcessModel;
import com.xbongbong.paas.service.stage.StageLogHandle;
import com.xbongbong.paas.service.stage.StageLogHandleFactory;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.PaasStageEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/05/26 16:39
 */
@Component
public class StageAverageStayTimeHelp {

    @Resource
    @Lazy
    private StageLogHandleFactory stageLogHandleFactory;
    @Resource
    private StageProcessModel stageProcessModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;

    /**
     * 获取当前阶段平均停留时长
     * date: 2022/1/18 5:07 下午
     * @Author yingjf
     * @param :
     */
    public String getAverageStayTime(Integer saasMark, Integer businessType, String corpid, Long formId, Long dataId, JSONObject data) throws XbbException {
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid", corpid);
        map.put("formId", formId);
        map.put("dataId", dataId);
        map.put("isNow", 1);
        map.put("del", 0);
        StageLogHandle stageLogHandle = stageLogHandleFactory.getStageLogHandle(saasMark, businessType);
        if (Objects.isNull(stageLogHandle)) {
            return null;
        }
        List<StageLogEntity> stageLogEntities = stageLogHandle.findEntitys(map);
        Long stageProcessId = data.getLong(PaasStageEnum.STAGE_PROCESS_ID.getAttr());
        PaasFormExplainEntity explain = paasFormExplainModel.getByFormId(formId, corpid);
        if (Objects.isNull(explain)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        FieldAttrEntity passStageAttr = ExplainUtil.getPassStageAttr(explain);
        if (Objects.isNull(passStageAttr)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.THIS_EXPLAIN_NOT_EXIST);
        }
        String stageCode = data.getString(passStageAttr.getAttr());
        StageProcessEntity stageProcessEntity = getStageProcessEntity(stageProcessId, stageCode, corpid, formId);
        if (CollectionUtils.isEmpty(stageLogEntities) || stageProcessEntity==null) {
            return null;
        }
        StageLogEntity stageLogEntity = stageLogEntities.get(0);
        Long historyStayTime = stageLogEntity.getHistoryStayTime();
        Long intoTime = stageLogEntity.getIntoTime();
        // 阶段停留时长
        return secondToTime(historyStayTime + DateTimeUtil.getInt() - intoTime, stageProcessEntity.getStageUnit());
    }

    /**
     * 按单位获取时间
     * date: 2022/1/6 9:49 上午
     * @Author yingjf
     * @param time: 秒级别的时间
     * @param stageUnit: 单位 【1时、2天、3周、4月】
     */
    public String secondToTime(long time, int stageUnit) {
        //阶段停留单位【1时、2天、3周、4月】
        switch (stageUnit) {
            case 1:
                return Arith.div(time, TimeConstant.SECONDS_PER_HOUR, 2) + I18nMessageUtil.getMessage(I18nStringConstant.UNIT_HOUR);
            case 2:
                return Arith.div(time, TimeConstant.SECONDS_PER_DAY, 2) + I18nMessageUtil.getMessage(I18nStringConstant.UNIT_DAY);
            case 3:
                return Arith.div(time, TimeConstant.SECONDS_PER_WEEK, 2) + I18nMessageUtil.getMessage(I18nStringConstant.UNIT_WEEK);
            case 4:
                return Arith.div(time, TimeConstant.SECONDS_PER_MONTH, 2) + I18nMessageUtil.getMessage(I18nStringConstant.UNIT_MONTH);
        }
        // 单位处理
        return DateUtil.secondToTime((int) time);
    }

    /**
     * 格式化阶段用时
     *
     * @param time
     * @return
     */
    public String formatTimeUse(long time) {
        if (time == 0) {
            return I18nMessageUtil.getMessage(CommonConstant.NOTHING);
        }
        // 单位处理
        return DateTimeUtil.getStringEpochSecond(time, DateTimeUtil.SDFYMDHM);
    }

    /**
     * description:  会有几种情况：
     * 1 data中有阶段流程id，那就是新产生的数据可以直接用，
     * 2.没有阶段流程id，但又阶段code，此时是老数据的情况（未刷的数据），需要用默认的迁移的阶段流程oldTransferVersion为1
     * 3.用启用的版本流程
     * date: 2021/12/31 10:28 上午
     *
     * @Author yingjf
     */
    private StageProcessEntity getStageProcessEntity(Long stageProcessId, String stageCode, String corpid, Long formId) throws XbbException {
        StageProcessEntity stageProcessEntity;
        if (Objects.nonNull(stageProcessId)) {
            stageProcessEntity = stageProcessModel.getByKey(stageProcessId, corpid);
        } else {
            // fix 少了一段，stageCode不为空，stageProcessId为空的逻辑
            // fix 这里会空指针，可能不存在启用的版本
            // stageCode 线索和客户需要传
            if (StringUtil.isNotEmpty(stageCode)) {
                stageProcessEntity = stageProcessModel.getOldTransferVersionProcess(stageProcessId, stageCode, corpid, formId);
            } else {
                stageProcessEntity = stageProcessModel.getEnableStageProcess(corpid, formId);
            }
        }
        return stageProcessEntity;
    }
}
